package com.jiot.plugin.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsResponse;

import com.jfinal.aop.Inject;
import com.jiot.common.model.dto.DeviceAlarmInfoDTO;
import com.jiot.common.model.dto.DeviceBasicInfoDTO;
import com.jiot.common.model.dto.DeviceHeartbeatInfoDTO;
import com.jiot.common.model.dto.DeviceIsOpenThresholdDTO;
import com.jiot.common.model.dto.DeviceSwitchInfoDTO;
import com.jiot.plugin.tio.MyWsMsgHandler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class MqttHandler {
	private static Logger log = LoggerFactory.getLogger(MqttHandler.class);

	public static final MqttHandler me = new MqttHandler();
	
	/**
	 * topic的末尾层是code，设备唯一嘛
	 */
	public void mqtt() {
		try {
	        //订阅设备基本信息（一般是设备上线后发一次）
			MqttKit.sub("/basic/+", MqttKit.QOS_EXACTLY_ONCE, new IMqttMessageListener() {		
	            public void messageArrived(String topic, MqttMessage message) throws Exception {
	            	String jsonStr = new String(message.getPayload());
	            	if(JSONUtil.isJson(jsonStr)) {
	            		DeviceBasicInfoDTO info = JSONUtil.toBean(jsonStr, DeviceBasicInfoDTO.class);
	            		if(StrUtil.isNotEmpty(info.getCode())) {
	            			System.out.println(info.getCode());
	            			//构造设备实体类
	            			//存或者覆盖mysql
	            		}
	            	}
	            }
	        });
			//订阅设备心跳信息（含有设备实时数据）
			MqttKit.sub("/heartbeat/+", MqttKit.QOS_AT_MOST_ONCE, new IMqttMessageListener() {		
	            public void messageArrived(String topic, MqttMessage message) throws Exception {
	            	String jsonStr = new String(message.getPayload());
	            	if(JSONUtil.isJson(jsonStr)) {
	            		DeviceHeartbeatInfoDTO info = JSONUtil.toBean(jsonStr, DeviceHeartbeatInfoDTO.class);
	            		if(StrUtil.isNotEmpty(info.getCode())) {
	            			System.out.println(info.getCode());
	            			//构造设备心跳实体类
	            			
	            			
	            			//存时序，
	            			
	            			
	            			//发websocket
	            			JSONObject obj = new JSONObject(info,false).putOpt("type", "heartbeat");
	            			WsResponse wsResponse = WsResponse.fromText(JSONUtil.toJsonStr(obj), "utf-8");
	            			MyWsMsgHandler.sendHeartbeat(wsResponse, "userid");
	            		}
	            	}
	            }
	        });
			//订阅设备报警信息
			MqttKit.sub("/alarm/+", MqttKit.QOS_EXACTLY_ONCE, new IMqttMessageListener() {		
	            public void messageArrived(String topic, MqttMessage message) throws Exception {
	            	String jsonStr = new String(message.getPayload());
	            	if(JSONUtil.isJson(jsonStr)) {
	            		DeviceAlarmInfoDTO basicInfo = JSONUtil.toBean(jsonStr, DeviceAlarmInfoDTO.class);
	            		if(StrUtil.isNotEmpty(basicInfo.getCode())) {
	            			System.out.println(basicInfo.getCode());
	            			//构造设备报警实体类
	            			//存时序，
	            			//发websocket
	            		}
	            	}
	            }
	        });
			//订阅设备的开关反馈的信息
			MqttKit.sub("/switch/+", MqttKit.QOS_EXACTLY_ONCE, new IMqttMessageListener() {		
	            public void messageArrived(String topic, MqttMessage message) throws Exception {
	            	String jsonStr = new String(message.getPayload());
	            	if(JSONUtil.isJson(jsonStr)) {
	            		DeviceSwitchInfoDTO info = JSONUtil.toBean(jsonStr, DeviceSwitchInfoDTO.class);
	            		if(StrUtil.isNotEmpty(info.getCode())) {
	            			System.out.println(info.getCode());
	            			//构造设备开关实体类
	            			//更新mysql，
	            			//跟新redis
	            			//发websocket
	            		}
	            	}
	            }
	        });
			//订阅阈值开关状态
			MqttKit.sub("/thresholdSwitch/+", MqttKit.QOS_EXACTLY_ONCE, new IMqttMessageListener() {		
	            public void messageArrived(String topic, MqttMessage message) throws Exception {
	            	String jsonStr = new String(message.getPayload());
	            	if(JSONUtil.isJson(jsonStr)) {
	            		DeviceIsOpenThresholdDTO info = JSONUtil.toBean(jsonStr, DeviceIsOpenThresholdDTO.class);
	            		if(StrUtil.isNotEmpty(info.getCode())) {
	            			System.out.println(info.getCode());
	            			//构造设备阈值开关实体类
	            			//更新mysql，
	            			//跟新redis
	            			//发websocket
	            		}
	            	}
	            }
	        });
			
			
			
			//发布消息
//			MqttKit.pub("/switch/11", "world".getBytes(), MqttKit.QOS_AT_LEAST_ONCE, false);
			
//			
	    } catch (MqttException e1) {
	        e1.printStackTrace();
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}
}
